<template >
	<div class="page_container">
		<!-- 搜索栏 开始 -->
		<div class="search_container">
			<el-form :inline="true" :model="searchData.formData" ref="searchForm" size="mini">
				<!-- 此处插入搜索需要的输入框 -->
				<el-form-item label="权限名称">
					<el-input v-model="searchData.formData.name"></el-input>
				</el-form-item>
				<el-form-item label="权限代码">
					<el-input v-model="searchData.formData.code"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" size="small" @click="searchSubmit()">查询</el-button>
					<el-button size="small" @click="clearSearchForm()">重置</el-button>
				</el-form-item>
			</el-form>
		</div>
		<!-- 搜索栏 结束 -->

		<!-- 按钮工具栏 开始 -->
		<div class="action_container" refs="actionContainer">
			<!-- 此处插入功能按钮等...
                可以使用权限套件控制显示
                v-anyPermission="[]"
                checkPermsisions([])
             -->
			<el-button type="primary" size="small" @click="showAddDrawer = true"> 新增{{ pageTitle }} </el-button>
		</div>
		<!-- 按钮工具栏 结束 -->

		<!-- 数据展示表格 开始 -->
		<div class="table_container">
			<el-table
				v-loading="tableLoading"
				:data="recordData.results"
				border
				:height="tableHeight"
				ref="recordTable"
				v-tableAutoHeight:[tableHeight]="125"
				:key="reloadKey"
			>
				<el-table-column label="选择框" type="selection" fixed></el-table-column>
				<el-table-column label="序号" type="index" width="50" fixed align="center"></el-table-column>

				<el-table-column label="权限名称" prop="name" align="center"></el-table-column>
				<el-table-column label="权限代码" prop="code" align="center"></el-table-column>
				<el-table-column label="权限分组名" prop="classify_name" align="center"></el-table-column>
				<el-table-column label="权限分组代码" prop="classify_code" align="center"></el-table-column>

				<!-- 此处插入表单
                可以使用权限套件控制显示
                v-anyPermission="[]"
                checkPermsisions([])
                 -->
				<el-table-column label="操作" width="150" fixed="right" align="center">
					<template #default="scope">
						<el-button size="mini" @click="handleEdit(scope.$index, scope.row)"> 编辑 </el-button>
						<el-popconfirm title="确定删除吗？" @confirm="rowDelete(scope.$index, scope.row)">
							<template #reference>
								<el-button size="mini" type="danger"> 删除 </el-button>
							</template>
						</el-popconfirm>
					</template>
				</el-table-column>
			</el-table>
		</div>
		<!-- 数据展示表格 结束 -->

		<!-- 分页 开始 -->
		<div class="pagination_container" refs="paginationContainer">
			<el-pagination
				@size-change="sizeChange()"
				@current-change="currentChange()"
				background
				layout="prev, pager, next, sizes, jumper"
				:total="recordData.count"
				v-model:pageSize="recordData.page_size"
				v-model:currentPage="recordData.page"
				:hide-on-single-page="false"
			>
			</el-pagination>
		</div>
		<!-- 分页 结束 -->

		<!-- 添加弹出层 开始 -->
		<el-drawer :title="'添加' + pageTitle" v-model="showAddDrawer" :show-close="false" destroy-on-close>
			<el-form class="add_form" :model="addData.formData" label-width="80px" ref="addForm" :rules="addData.rules">
				<el-form-item label="权限名称" prop="name">
					<el-input
						v-model="addData.formData.name"
						@blur="AddFormTranslationChinasesToPinYin(addData.formData.name, 'code')"
					></el-input>
				</el-form-item>
				<el-form-item label="权限代码" prop="code">
					<el-input v-model="addData.formData.code"></el-input>
				</el-form-item>
				<el-form-item label="权限分组名称" prop="classify_name">
					<el-input
						v-model="addData.formData.classify_name"
						@blur="AddFormTranslationChinasesToPinYin(addData.formData.classify_name, 'classify_code')"
					></el-input>
				</el-form-item>
				<el-form-item label="权限分组代码" prop="classify_code">
					<el-input v-model="addData.formData.classify_code"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" size="small" @click="addSubmit()">提交</el-button>
				</el-form-item>
			</el-form>
		</el-drawer>
		<!-- 添加弹出层 结束 -->

		<!-- 修改弹出层 开始 -->
		<el-drawer :title="'修改' + pageTitle" v-model="showChangeDrawer" :show-close="false" destroy-on-close>
			<el-form
				class="change_form"
				:model="changeData.formData"
				label-width="80px"
				ref="changeForm"
				:rules="changeData.rules"
			>
				<el-form-item label="权限名称" prop="name">
					<el-input
						v-model="changeData.formData.name"
						@blur="ChangeFormTranslationChinasesToPinYin(changeData.formData.classify_name, 'name')"
					></el-input>
				</el-form-item>
				<el-form-item label="权限代码" prop="code">
					<el-input v-model="changeData.formData.code"></el-input>
				</el-form-item>
				<el-form-item label="权限分组名称" prop="classify_name">
					<el-input
						v-model="changeData.formData.classify_name"
						@blur="
							ChangeFormTranslationChinasesToPinYin(changeData.formData.classify_name, 'classify_code')
						"
					></el-input>
				</el-form-item>
				<el-form-item label="权限分组代码" prop="classify_code">
					<el-input v-model="changeData.formData.classify_code"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" size="small" @click="changeSubmit()">提交</el-button>
				</el-form-item>
			</el-form>
		</el-drawer>
		<!-- 修改弹出层 结束 -->
	</div>
</template>
<script>
import { ElMessage } from 'element-plus'
import { list, remove, retrieve, create, put, patch } from '@/apis/curd'
import { anyPermission } from '@/utils/permission'
var pinyin = require('pinyin')

export default {
	name: 'Permission',
	data() {
		return {
			// 用于自动设置表格高度
			tableHeight: 100,
			reloadKey: 1,
			// 页面配置项
			pageTitle: '权限',
			uri: 'auth/permission', // 请求的基础地址 /<uri>
			key: 'code', // 加在请求后面的主键key /<uri>/<key>
			showAddDrawer: false, // 控制是否打开添加表单抽屉
			showChangeDrawer: false, // 控制是否打开修改表单抽屉
			selectRow: null, // 编辑/删除时行数据会保存在这里
			tableLoading: false,
			searchData: {
				formData: {
					code: null,
					name: null,
				},
				source: {},
			}, // 搜索工具栏数据
			recordData: { page: 1, page_size: 20, count: 0, results: [] }, // 展示数据及分页数据
			addData: {
				formData: {
					name: null,
					code: null,
					classify_name: null,
					classify_code: null,
				},
				source: {},
				rules: {
					name: [
						{ required: true, message: '请输入权限名称', trigger: 'blur' },
						{ min: 4, max: 32, message: '长度在 4 到 32 个字符', trigger: 'blur' },
					],
					code: [
						{ required: true, message: '请输入权限代码', trigger: 'blur' },
						{ min: 4, max: 128, message: '长度在 4 到 128 个字符', trigger: 'blur' },
					],
					classify_name: [
						{ required: true, message: '请输入权限分类名称', trigger: 'blur' },
						{ min: 4, max: 32, message: '长度在 4 到 32 个字符', trigger: 'blur' },
					],
					classify_code: [
						{ required: true, message: '请输入权限分类代码', trigger: 'blur' },
						{ min: 4, max: 128, message: '长度在 4 到 128 个字符', trigger: 'blur' },
					],
				},
			}, // 用于添加的数据
			changeData: {
				formData: {
					name: null,
					code: null,
					classify_name: null,
					classify_code: null,
				},
				source: {},
				rules: {
					name: [
						{ required: true, message: '请输入权限名称', trigger: 'blur' },
						{ min: 4, max: 32, message: '长度在 4 到 32 个字符', trigger: 'blur' },
					],
					code: [
						{ required: true, message: '请输入权限代码', trigger: 'blur' },
						{ min: 4, max: 128, message: '长度在 4 到 128 个字符', trigger: 'blur' },
					],
					classify_name: [
						{ required: true, message: '请输入权限分类名称', trigger: 'blur' },
						{ min: 4, max: 32, message: '长度在 4 到 32 个字符', trigger: 'blur' },
					],
					classify_code: [
						{ required: true, message: '请输入权限分类代码', trigger: 'blur' },
						{ min: 4, max: 128, message: '长度在 4 到 128 个字符', trigger: 'blur' },
					],
				},
			}, // 用于修改的数据
		}
	},
	mounted() {
		// 渲染结束后钩子函数
		this.autoHeightHandle()
		this.searchSubmit()
	},
	methods: {
		AddFormTranslationChinasesToPinYin(value, key) {
			let code = pinyin(value, { style: pinyin.STYLE_NORMAL })
			if (!this.addData.formData[key]) {
				this.addData.formData[key] = code.join('_')
			}
		},
		ChangeFormTranslationChinasesToPinYin(value, key) {
			let code = pinyin(value, { style: pinyin.STYLE_NORMAL })
			if (!this.changeData.formData[key]) {
				this.changeData.formData[key] = code.join('_')
			}
		},
		// 搜索请求
		searchSubmit() {
			// 构造分页及筛选数据
			this.tableLoading = true
			let data = { page: this.recordData.page, page_size: this.recordData.page_size }
			for (let i in this.searchData.formData) {
				let val = this.searchData.formData[i]
				if (val) {
					data[i] = val
				}
			}
			//  发起请求
			list(this.uri, data, false)
				.then(res => {
					// 处理成功数据
					this.recordData = res.data.recordData
					this.addData.source = res.data.addData
					this.changeData.source = res.data.changeData
					this.searchData.source = res.data.searchData
					this.tableLoading = false
				})
				.catch(respons => {
					// 处理失败数据
					this.tableLoading = false
				})
		},
		// 清空搜索工具栏
		clearSearchForm() {
			for (let i in this.searchData.formData) {
				this.searchData.formData[i] = null
			}
		},
		// 点击删除键时触发的事件
		rowDelete(index, row) {
			remove(this.uri, row[this.key])
				.then(res => {
					if (res.status) {
						this.recordData.results.splice(index, 1)
						ElMessage.success({
							message: '删除成功',
						})
					} else {
						ElMessage.error({
							message: res.message,
						})
					}
				})
				.catch(respons => {
					console.log(respons)
				})
		},
		// 分页的记录条数发生变化时触发
		sizeChange() {
			this.searchSubmit()
		},
		// 分页的页码发生变化时触发
		currentChange() {
			this.searchSubmit()
		},
		// 点击编辑时触发的方法
		handleEdit(index, row) {
			retrieve(this.uri, row[this.key]).then(res => {
				if (res.status) {
					this.selectRow = row
					this.showChangeDrawer = true
					for (let i in this.changeData.formData) {
						this.changeData.formData[i] = res.data[i]
					}
				} else {
					ElMessage.error({
						message: res.message,
					})
				}
			})
		},
		// 执行添加提交
		addSubmit() {
			this.$refs['addForm'].validate(valid => {
				if (valid) {
					create(this.uri, this.addData.formData).then(res => {
						if (res.status) {
							ElMessage.success({
								message: '添加成功',
							})
							this.searchSubmit()
							this.showAddDrawer = false
						} else {
							ElMessage.error({
								message: res.message,
							})
						}
					})
				}
			})
		},
		// 执行修改提交
		changeSubmit() {
			this.$refs['changeForm'].validate(valid => {
				if (valid) {
					patch(this.uri, this.selectRow[this.key], this.changeData.formData).then(res => {
						if (res.status) {
							ElMessage.success({
								message: '修改成功',
							})
							this.searchSubmit()
							this.showChangeDrawer = false
						} else {
							ElMessage.error({
								message: res.message,
							})
						}
					})
				}
			})
		},
		//  工具方法
		checkPermsisions(values) {
			// 检查是否有权限
			if (Array.isArray(values)) {
				return anyPermission(values)
			}
			return false
		},
		concatList(o, t) {
			// 合并数组 arry
			if (Array.isArray(o) && Array.isArray(t)) {
				return o.concat(t)
			} else if (Array.isArray(o)) {
				return o
			} else if (Array.isArray(t)) {
				return t
			} else {
				return []
			}
		},
		autoHeightHandle() {
			// 自动设置表格的高度
			let el = this.$refs.recordTable.$el
			let clientHeight = document.body.clientHeight
			let elOffsetTop = el.offsetTop
			let height_the_left = clientHeight - elOffsetTop
			let elH = height_the_left - 145
			el.style = `height:calc(${elH}px - 2rem);overflow-y:auto;`
			this.tableHeight = elH - 12
			this.reloadKey++
			this.$refs.recordTable.doLayout()
		},
	},
}
</script>
<style lang='scss' scoped>
.search_container {
	padding: 1rem 1rem 0 1rem;
	background-color: white;
	border-bottom: 1px #f2f6fc solid;
	line-height: 1rem;
}
.action_container {
	padding: 0.5rem 1rem;
	background-color: #f5f7fa99;
	background-color: white;
}
.table_container {
	// padding: 0rem 2rem 1rem 2rem;
	background-color: white;
	padding: 0 1rem;
}
.pagination_container {
	padding: 1rem 4rem 1rem 0rem;
	background-color: white;
	text-align: center;
}
.add_form,
.change_form {
	padding-right: 2rem;
}
:deep(.el-drawer__body) {
	overflow-x: auto;
}
.inline-block {
	display: inline-block;
}
</style>